﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using KBVault.DAL.Repository;
using System.Web.Security;
using KBVault.Web.Infrastructure;

namespace KBVault.Web.Application
{
    public partial class Login : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void btnLogin_Click(object sender, EventArgs e)
        {
            if (UserRepository.Validate(UserName.Text, Password.Text))
            {
                DateTime issueDate = DateTime.Now;
                DateTime expirationDate = issueDate.AddHours(24);
                var user = UserRepository.Get(UserName.Text);
                var ticket = new FormsAuthenticationTicket(0, UserName.Text, issueDate, expirationDate, RememberMe.Checked, user.Id.ToString(), FormsAuthentication.FormsCookiePath);
                string encryptedTicket = FormsAuthentication.Encrypt(ticket);
                var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket)
                {
                    Domain = FormsAuthentication.CookieDomain,
                    Path = FormsAuthentication.FormsCookiePath,
                    Expires = expirationDate
                };
                UserRepository.SetUserLoggedIn(user);
                SessionManager.SetCurrentUser(user);
                Response.Cookies.Add(cookie);
                if (Request.QueryString["ReturnUrl"] != null)
                    Response.Redirect(Request.QueryString["ReturnUrl"].ToString());
                Response.Redirect("~/Application/CategoryOps.aspx?Op=list");
            }
            else
            {
                Response.Redirect("login.aspx");
            }
        }
        /*
         
         */


    }
}